package com.hnu.tockmarket.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.hnu.tockmarket.R;
import com.hnu.tockmarket.constant.SystemConstants;
import com.hnu.tockmarket.entity.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 登陆页面对应的活动
 *
 * @author hnulht
 * @since 2021-07-08
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "LoginActivity"; // 日志
    private Intent intent = null;
    private EditText editTextName; // 用户名输入框
    private EditText editTextPassword; // 用户密码输入框
    private Button buttonLogin; // 用户登录按钮
    private Button buttonRegister; // 用户注册按钮
    private ProgressDialog progressDialog; // 登录加载控件
    private static final int LOGIN_OK = 1; // 表示用户登录成功
    private static final int LOGIN_ERROR = 0; // 表示用户登录失败
    private String inputName = ""; // 临时存储用户输入的名字
    private String inputPassword = ""; // 临时存储用户输入的密码
    private final SystemHandler systemHandler = new SystemHandler(); // 将数据从子线程抛到主线程中

    private class SystemHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message message) {
            super.handleMessage(message);
            switch (message.what) {
                case LOGIN_OK:
                    Log.d(TAG, "[SystemHandler.handleMessage]主线程处理子线程传送的信息" + (String) message.obj);
                    // 解析服务器传回的JSON格式数据
                    String restResponse = (String) message.obj;
                    parseJSON(restResponse);
                    break;
                case LOGIN_ERROR:
                    Log.d(TAG, "[SystemHandler.handleMessage]主线程处理子线程传送的信息" + (String) message.obj);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); // 调用父类onCreate()方法
        setContentView(R.layout.activity_login); // 给登录页面活动加载对应的布局
        initView(); // 初始化视图
    }

    /**
     * 初始化视图
     */
    private void initView() {
        // 定位用户名和密码输入框
        editTextName = (EditText) findViewById(R.id.login_name_et);
        editTextPassword = (EditText) findViewById(R.id.login_password_et);
        // 定位用户登录按钮并设置点击事件
        buttonLogin = (Button) findViewById(R.id.login_login_btn);
        buttonLogin.setOnClickListener(this);
        // 定位用户注册按钮并设置点击事件
        buttonRegister = (Button) findViewById(R.id.login_register_btn);
        buttonRegister.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_login_btn:
                checkUserLogin(); // 检查用户提交的登录信息
                break;
            case R.id.login_register_btn:
                // 跳转到注册页面
                intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 检查用户提交的登录信息
     */
    private void checkUserLogin() {
        inputName = editTextName.getText().toString().trim(); // 获取用户输入的名字
        if (TextUtils.isEmpty(inputName)) {
            Toast.makeText(LoginActivity.this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        }
        inputPassword = editTextPassword.getText().toString().trim(); // 获取用户输入的密码
        if (TextUtils.isEmpty(inputPassword)) {
            Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 向服务器发送请求
                    String url = SystemConstants.SERVER_BASE_URL + "/user/login";
                    OkHttpClient okHttpClient = new OkHttpClient();
                    // 封装请求信息为json对象
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("name", inputName);
                    jsonObject.put("password", inputPassword);
                    // 构建请求体
                    MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
                    RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
                    Request request = new Request.Builder().url(url).post(requestBody).build();
                    // 服务器传回的响应信息
                    Response response = okHttpClient.newCall(request).execute();
                    assert response.body() != null;
                    String restResponse = response.body().string();
                    Log.d(TAG, "[checkUserLogin.run]子线程得到服务器传回的JSON数据" + restResponse);
                    // 向主线程发送服务器传回的响应信息
                    Message message = new Message();
                    message.what = LOGIN_OK;
                    message.obj = restResponse;
                    systemHandler.sendMessage(message);
                } catch (JSONException | IOException e) {
                    Message message = new Message();
                    message.what = LOGIN_ERROR;
                    message.obj = e.getMessage();
                    systemHandler.sendMessage(message);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 解析服务器传回的JSON格式数据
     *
     * @param restResponse JSON格式数据
     */
    private void parseJSON(String restResponse) {
        try {
            Log.d(TAG, "[parseJSON]主线程解析服务器传回的JSON格式数据" + restResponse);
            JSONObject jsonObject = new JSONObject(restResponse);
            if (jsonObject.getInt("statusCode") == 200) {
                Gson gson = new Gson();
                User user = gson.fromJson(jsonObject.getString("responseData"), User.class);
                // 登陆成功后把信息保存到本地
                SharedPreferences.Editor editor = getSharedPreferences("login_data", MODE_PRIVATE).edit();
                editor.putString("id", user.getId());
                editor.putString("name", user.getName());
                editor.putString("password", user.getPassword());
                editor.putString("role", user.getRole());
                editor.putString("email", user.getEmail());
                editor.putString("phoneNumber", user.getPhoneNumber());
                editor.putString("salt", user.getSalt());
                editor.putString("lastLoginTime", user.getLastLoginTime());
                editor.putString("createTime", user.getCreateTime());
                editor.putString("updateTime", user.getUpdateTime());
                editor.apply();
                // 定位登录加载控件并设置延时取消
                progressDialog = new ProgressDialog(LoginActivity.this);
                progressDialog.setMessage("登录中...");
                progressDialog.setCancelable(false);
                progressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000); // 显示2秒后取消加载
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        progressDialog.dismiss();
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }).start();
            } else if (jsonObject.getInt("statusCode") == 403) {
                Toast.makeText(LoginActivity.this, "密码不正确", Toast.LENGTH_SHORT).show();
            } else if (jsonObject.getInt("statusCode") == 404) {
                Toast.makeText(LoginActivity.this, "用户未注册", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(LoginActivity.this, "服务器内部错误", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}